﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using DynamicLoader.DataStructures;
using DynamicLoader;
namespace SSCCMembership
{
    public partial class Login : UserControl
    {
        public Login()
        {
            InitializeComponent();
            txtUsername.Focus();
        }

        #region Page Logic
        private bool SignInInProgress
        {
            get { return !txtUsername.IsEnabled; }
            set
            {
                txtUsername.IsEnabled = !value;
                txtPassword.IsEnabled = !value;
                BTN.IsEnabled = !value;
            }
        }
        public event EventHandler LoggedIn;
        public void DoSignIn()
        {
            if (!SignInInProgress)
            {
                if (txtUsername.Text.Length > 0 && txtPassword.Password.Length > 0)
                {
                    BusyIndicator.Show("Attempting to Log In");
                    SignInInProgress = true;

                    try
                    {
                        Cache.Stop();
                        //Services.Authentication.AuthenticationServiceClient ASC = new Services.Authentication.AuthenticationServiceClient();
                        Services.Login.LoginServiceClient ASC = new Services.Login.LoginServiceClient();
                        ASC.LoginCompleted += (s, ea) =>
                        {
                            BusyIndicator.Hide();
                            SignInInProgress = false;
                            if (ea.Error != null)
                            {
                                Cache.Start();
                                //HandleError
                                //DataContext = "Technical Error";
                                DataContext = ea.Error.GetBaseException().Message;
                                //"There was a technical Error" 
                                BusyIndicator.Show(() => txtUsername.Focus(),ea.Error.GetBaseException().ToString(), false, 20, true);
                                //ShowMessage("There was a technical Error", new TimeSpan(0, 0, 2), new Action(() =>
                                //{
                                //    txtUsername.Focus();
                                //}
                                //));
                            }
                            else
                            {
                                if (!ea.Result.Success)
                                {
                                    DataContext = ea.Result.FailureMessage;
                                    //"There was a technical Error" 
                                    BusyIndicator.Show(() => txtUsername.Focus(), ea.Result.FailureMessage, false, 20, true);
                                    return;
                                }
                                if (ea.Result.Value)
                                {
                                    //Success
                                    //App.Username = txtUsername.Text;
                                    //if (!DownloadStarted)
                                    //{
                                    //    DownloadStarted = true;
                                    //}
                                    //if (this.LoggedIn != null)
                                    //{
                                    //    this.LoggedIn(this, EventArgs.Empty);
                                    //}
                                    DataContext = "Success";
                                    //ShowPermaMessage("Success, Checking Security Permissions");
                                    BusyIndicator.Show("Success, Checking Security Permissions");
                                    //LoadRoles
                                    Services.Abilities.AbilitiesServiceClient AbSC = new Services.Abilities.AbilitiesServiceClient();
                                    AbSC.GetAbilitiesCompleted += (sab, eab) =>
                                        {
                                            BusyIndicator.Hide();
                                            //CloseMessage();
                                            if (!eab.Cancelled & eab.Error == null)
                                            {
                                                SecurityLib.Security.UserRoles = eab.Result;
                                                LoggedIn(this, EventArgs.Empty);
                                            }
                                            else
                                            {
                                                SecurityLib.Security.UserRoles = new List<string>();
                                                //ShowMessage("There was a problem obtaining Roles, you have been logged in with the minimum security privelages", new TimeSpan(0, 0, 10), () => { LoggedIn(this, EventArgs.Empty); });
                                                BusyIndicator.Show(() => LoggedIn(this, EventArgs.Empty), "There was a problem obtaining Roles, you have been logged in with the minimum security privelages", false, 10, true);
                                            }
                                        };
                                    AbSC.GetAbilitiesAsync();

                                    //Services.Roles.RoleServiceClient RSC = new Services.Roles.RoleServiceClient();
                                    //RSC.GetRolesForCurrentUserCompleted += (sr, er) => 
                                    //{
                                    //    CloseMessage();
                                    //    if (!er.Cancelled & er.Error == null)
                                    //    {
                                    //        SecurityLib.Security.UserRoles = er.Result;
                                    //        LoggedIn(this, EventArgs.Empty);
                                    //    }
                                    //    else
                                    //    {
                                    //        SecurityLib.Security.UserRoles = new List<string>();
                                    //        ShowMessage("There was a problem obtaining Roles, you have been logged in with the minimum security privelages", new TimeSpan(0, 0, 10), () => { LoggedIn(this, EventArgs.Empty); });
                                    //    }
                                    //};
                                    //RSC.GetRolesForCurrentUserAsync();
                                }
                                else
                                {
                                    Cache.Start();
                                    //Failure
                                    DataContext = "Your Username or Password was incorrect";
                                    BusyIndicator.Show(() =>
                                    {
                                        txtUsername.Text = "";
                                        txtPassword.Password = "";
                                        txtUsername.Focus();
                                    }, "Your Username or Password was incorrect", false, 2, true);
                                    //ShowMessage("Your Username or Password was incorrect", new TimeSpan(0, 0, 2), new Action(() =>
                                    //{
                                    //    txtUsername.Text = "";
                                    //    txtPassword.Password = "";
                                    //    txtUsername.Focus();
                                    //}
                                    //));
                                }
                            }
                        };
                        ASC.LoginAsync(txtUsername.Text, txtPassword.Password, null, false, txtUsername.Text);
                    }
                    catch (Exception)
                    {
                        BusyIndicator.Hide();
                        SignInInProgress = false;
                    }
                }
            }
        }
        #endregion

        #region Login Events
        private void Login_Click(object sender, RoutedEventArgs e)
        {
            DoSignIn();
        }
        private void SignIn_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                DoSignIn();
            }
        }
        #endregion


        private void Image_ImageOpened(object sender, RoutedEventArgs e)
        {
            //Begin Loaidng XAPs
            //Cache.Start();
            //List<Dependancy> Dependancies = new List<Dependancy>()
            //{
            //    new Dependancy("System.Windows.Controls.xap", new AssemblyName[0], 0),
            //    new Dependancy("System.Windows.Controls.xap", new AssemblyName[0], 0),
            //};
            //DynamicLoader.ListLoader LL = new DynamicLoader.ListLoader(Dependancies, new LLCallback());
        }


        class LLCallback:DynamicLoader.IListLoaderCallback
        {

            #region IListLoaderCallback Members

            public void OnCompleted()
            {
            }

            public void OnFileSizeChanged(long FileSize)
            {
            }

            public void OnProgressChanged(long TotalBytesRecieved, long Increase)
            {
            }

            #endregion
        }

    }

    //static class ExceptionExtension
    //{
    //    public static Exception GetBase(this Exception ex)
    //    {
    //        if (ex.InnerException != null)
    //        {
    //            return GetBase(ex.InnerException);
    //        }
    //        else
    //        {
    //            return ex;
    //        }
    //    }
    //}


}
